#include "FileHandler.h"
#include <QFile>
#include <QCoreApplication>


namespace
{
QString BACKUP_SUFFIX = ".bak";
}

FileHandler::FileHandler(QObject *parent) :
    QObject(parent)
{
    m_serializer = 0;
}



void FileHandler::installSerializer(AbstractSerializer *serializer)
{
    if (instance()->m_serializer)
    {
        instance()->m_serializer->deleteLater();
        instance()->m_serializer = 0;
    }

    if (!serializer) return;

    instance()->m_serializer = serializer;
    instance()->m_serializer->setParent(instance());
}



bool FileHandler::save(const QString &file_path, AbstractItem *item)
{
    if (!item)
    {
        qDebug("Item is null");
        return false;
    }

    if (instance()->m_serializer.isNull())
    {
        qDebug("Serializer is null");
        return false;
    }


    if (QFile::exists(file_path + BACKUP_SUFFIX))
    {
        QFile::remove(file_path + BACKUP_SUFFIX);
    }

    if (QFile::exists(file_path))
    {
        QFile::copy(file_path, file_path + BACKUP_SUFFIX);
        QFile::remove(file_path);
    }

    QFile output(file_path);
    if (!output.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug("Failed to open output");
        return false;
    }

    instance()->m_serializer->serialize(item, &output);

    output.close();
    return true;
}



AbstractItem* FileHandler::open(const QString &file_path)
{
    if (instance()->m_serializer.isNull()) return 0;

    QFile input(file_path);
    if (!input.exists()) return 0;
    if (!input.open(QFile::ReadOnly | QFile::Text)) return 0;

    AbstractItem* root = instance()->m_serializer->deserialize(&input);
    input.close();

    return root;
}



FileHandler* FileHandler::instance()
{
    static FileHandler* fh = 0;
    if (!fh) fh = new FileHandler(qApp);

    return fh;
}
